package com.app.couponsharelife.ui.main.home.local

import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.manager.LifecycleListener
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.LifeShopPageBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.LocalShopDetailAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.view.BannerView
import com.app.couponsharelife.ui.viewmodel.LocalViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_local_shop_detail.*
import java.util.HashMap

class LocalShopDetailActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_local_shop_detail

    private var mViewModel: LocalViewModel? = null

    private var shopId = ""

    private var mobile = ""

    private var shopName = ""

    /**
     * 轮播图数据
     */
    private var bannerTop: MutableList<LifeShopPageBean.BannersBean> = mutableListOf()

    /**
     * 顶部轮播图监听
     */
    private var listenerTop: LifecycleListener? = null

    override fun initViews() {
        if (intent.getStringExtra("shopId") != null)
            shopId = intent.getStringExtra("shopId")
        else {
            showToastMsg("数据错误，请退出重试")
            finish()
        }
        tvBuy.setOnClickListener {
            val intent = Intent(this, LocalShopPayActivity::class.java)
            intent.putExtra("shopId", shopId)
            intent.putExtra("mobile", mobile)
            intent.putExtra("shopName", shopName)
            startActivity(intent)
//            val intent = Intent(this, CouponDetailActivity::class.java)
//            intent.putExtra("couponId", "1")
//            startActivity(intent)
        }
        ivBack.setOnClickListener { finish() }
        initRecyclerView()
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.adapter = LocalShopDetailAdapter(arrayListOf(PageTipBean("", 0, 0)), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                startActivity(Intent(this@LocalShopDetailActivity, CouponDetailActivity::class.java))
            }
        })
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(LocalViewModel::class.java)
        if (!mViewModel!!.userCenter()!!.hasObservers()) {
            mViewModel!!.userCenter()!!.observe(this, Observer {
                if (it == null) {
                    handleError(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        handleError(parseErrorDate("暂无数据"))
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            mobile = it.data.data!!.mobile
                            loadData(it.data.data!!.mobile)
                        } else {
                            handleError(parseErrorDate("暂无店铺信息"))
                        }
                    }
                }
            })
            mViewModel!!.getLifeShopInfo()!!.observe(this, Observer {
                if (it == null) {
                    handleError(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetLifeShopInfo(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetLifeShopInfo(hashMapOf(), false)
                        handleError(parseErrorDate("暂无数据"))
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetLifeShopInfo(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            handleError(parseErrorDate("暂无店铺信息"))
                        }
                    }
                }
            })
        }
        userCenter()
    }

    private fun userCenter() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.freshUserCenter(map, true)
    }

    private fun loadData(phone: String) {
        val map = HashMap<String, String>()
        map["shopId"] = shopId
        map["mobile"] = phone
        mViewModel?.freshGetLifeShopInfo(map, true)
    }

    private fun handleContent(data: LifeShopPageBean.RecordsBean) {
        tvToolBarTitle.text = data.shopName
        shopName = data.shopName!!
        if (data.listImages.isNotEmpty()) {
            initBannerTop(data.listImages)
        }
        (mRecyclerView.adapter as LocalShopDetailAdapter).setData(data)
    }

    private fun handleError(pageTipBean: PageTipBean) {
        if ((mRecyclerView.adapter as LocalShopDetailAdapter).list[0] is PageTipBean) {
            ((mRecyclerView.adapter as LocalShopDetailAdapter).list[0] as PageTipBean).tip = pageTipBean.tip
            ((mRecyclerView.adapter as LocalShopDetailAdapter).list[0] as PageTipBean).status = pageTipBean.status
            ((mRecyclerView.adapter as LocalShopDetailAdapter).list[0] as PageTipBean).src = pageTipBean.src
            (mRecyclerView.adapter as LocalShopDetailAdapter).notifyItemChanged(0)
        } else {
            showToastMsg(pageTipBean.tip)
        }
    }

    private fun initBannerTop(images: List<String>) {
        mBanner.start(images)
        mBanner.onStart()
        registerLifeListenerTop(mBanner)
        mBanner.onPageClickListener = object : BannerView.OnPageClickListener {
            override fun click(position: Int) {

            }
        }
    }

    private fun registerLifeListenerTop(listener: LifecycleListener) {
        this.listenerTop = listener
        listenerTop?.onStart()
    }
}
